Ext.define('Service.user.controller.UserController', {
	extend: 'WebOs.ex.DefaultController',
	
	/*********************************引用部分Start*************************************/
	views : [
		 'Service.user.view.UserInfoEditForm',
		 'Service.user.view.UserEditTabs',
         'Service.user.view.InitContainer',
         'Service.user.view.UserDataListGrid',
         'Service.user.view.UserEditWindow',
         'Service.user.view.UserRoleEditContainer',
         'Service.user.view.RoleDataListGrid',
         'Service.user.view.UserAuthTree',
         'Service.user.view.UserAuthEditContainer'
	],
	
	stores : [
		'Service.user.store.CardTypeValueStore',
		'Service.user.store.UserDataListStore'
	],
	
	models : [
		'Service.user.model.UserModel',
		'Service.user.model.RoleModel',
		'Service.user.model.AuthTreeModel'
	],
	
	refs : [
			{ref : 'userRoleEditContainer', selector : 'Service_user_view_UserRoleEditContainer'},
	        {ref : 'userEditForm', selector : 'Service_user_view_UserInfoEditForm'},
	        {ref : 'userEditTabs', selector : 'Service_user_view_UserEditTabs'},
	        {ref : 'userEditWindow', selector : 'Service_user_view_UserEditWindow'},
	        {ref : 'userList', selector : 'Service_user_view_UserDataListGrid'},
	        {ref : 'allRoleGrid', selector : 'Service_user_view_RoleDataListGrid[id=Service_user_view_NotAddRoleDataListGrid]'},
	        {ref : 'selectRoleGrid', selector : 'Service_user_view_RoleDataListGrid[id=Service_user_view_AddRoleDataListGrid]'},
	        {ref : 'allAuthTree', selector : 'Service_user_view_UserAuthTree[id=Service_user_view_UserAuthTree_All]'},
	        {ref : 'selectAuthTree', selector : 'Service_user_view_UserAuthTree[id=Service_user_view_UserAuthTree_Selected]'}
	],
	/*********************************引用部分End*************************************/
	
	/*********************************事件监听Start*************************************/
	init: function() {
		var me=this;
        this.control({
        	'button[id=Service_user_btn_active_prevUserEditTab]':{
        		//上一步
        		click : me.onBtnActivePrevUserEditTabFire
        	},
        	'button[id=Service_user_btn_active_nextUserEditTab]':{
        		//下一步
        		click : me.onBtnActiveNextUserEditTabFire
        	},
            'button[id=Service_user_btn_show_UserAddWindow]': {
            	//弹出用户添加窗口
                click : me.onBtnShowUserAddWindowFire
            },
            'button[id=Service_user_btn_show_UserChgWindow]': {
            	//弹出用户修改窗口
                click : me.onBtnShowUserChgWindowFire
            },
            'button[id=Service_user_btn_batchDel_Users]' : {
            	//批量删除用户
            	click : me.onBtnDelUsersFire
            },
            'button[id=Service_user_btn_add_UserRole]':{
            	//角色选择
            	click : me.onBtnAddUserRoleFire
            },
            'button[id=Service_user_btn_del_UserRole]':{
            	//角色删除
            	click : me.onBtnDelUserRoleFire
            },
            'Service_user_view_UserEditTabs' : {
            	//TAB切换
            	tabchange :  me.onUserEditTabChangeFire
            },
            'Service_user_view_UserEditWindow' : {
            	//数据初始化
            	beforeshow : me.onUserEditWindowBeforeshowFire,
            	//关闭确认
            	beforeclose : me.onConfirmWindowBeforeClose
            },
            'Service_user_view_UserAuthTree[id=Service_user_view_UserAuthTree_All]' : {
            	//权限选择
            	checkchange : me.onUserAuthTreeCheckChgFire
            },
            'button[id=Service_user_btn_save_userInfo]' :  {
            	//保存用户信息
            	click : me.onBtnSaveUserInfoFire
            },
            'Service_user_view_RoleDataListGrid' : {
            	select : me.onGridSelectRowFire
            }
            //------------------------------------------------
            //------------------------------------------------
            //------------------------------------------------
            //------------------------------------------------
            
        });
    },
    onDelUsersConfirm : function(buttonId){
    	var me=this;
    	if(buttonId == 'ok'){
    		//执行批量删除
    		var userList = me.getUserList();
    		//var userListStore = userList.getStore();
    		var selModel = userList.getSelectionModel();
    		var models = selModel.getSelection();
    		var ids = [];
    		for(var p in models){
    			ids.push(models[p].get('id'));
    		}
    		me.delBatchUsers(ids);
    	}
    },
    /*********************************事件监听End*************************************/
    
    /*********************************事件监听触发函数Start*************************************/
    onBtnActivePrevUserEditTabFire : function(btn,evt,opts){
    	var me = this;
    	var tab = me.getUserEditTabs();
    	var prevTab = tab.getActiveTab().previousSibling();
    	me.activeUserEditTab(tab,prevTab);
    	me.setWindowNavButtonDisabled(prevTab);
    },
    onBtnActiveNextUserEditTabFire : function(btn,evt,opts){
    	var me = this;
    	var tab = me.getUserEditTabs();
    	var nextTab = tab.getActiveTab().nextSibling();
    	me.activeUserEditTab(tab,nextTab);
    	me.setWindowNavButtonDisabled(nextTab);
    },
    onBtnShowUserAddWindowFire : function(btn,evt,opts){
    	var me=this;
    	var win = btn.up('window');
    	var cfg = {title : '添加用户',icon : Constants.SER_RES_PATH + 'icon/share/user_add.gif',window_action : 'add',userId : null,parent:win};
    	return me.showUserEditWindow(cfg);
    },
    onBtnShowUserChgWindowFire : function(btn,evt,opts){
    	var me=this;
    	var grid = me.getUserList();
    	var selModel = grid.getSelectionModel();
		var models = selModel.getSelection();
		if(!models || models.length!=1){
			ShowInfoMsg('修改提示','必须选择一个用户进行修改');
			return false;
		}
		var record = models[0];
		var userId = record.get('id');
    	var cfg = {title : '修改用户',icon : Constants.SER_RES_PATH + 'icon/share/user_edit.png',window_action : 'chg','userId' : userId,'record' : record};
    	return me.showUserEditWindow(cfg);
    },
    
    onUserEditTabChangeFire : function(tab,newc,oldc){
    	var me = this;
    	me.setWindowNavButtonDisabled(newc);
    	return true;
    },
    onGridSelectRowFire : function(rowModel,record,rowNum,opts){
    	var me = this;
    	me.setUserRoleInfoDisplay(record.get('roleText')+'：'+record.get('remark'));
    },
    
    onBtnAddUserRoleFire : function(btn,evt,opts){
    	var me = this;
    	var srcGrid = me.getAllRoleGrid();
    	var targetGrid = me.getSelectRoleGrid();
    	me.moveGridSelectedDataToOtherGrid(srcGrid,targetGrid);
    	me.setUserEditDirty();
    },
    onBtnDelUserRoleFire : function(btn,evt,opts){
    	var me = this;
    	var srcGrid = me.getSelectRoleGrid();
    	var targetGrid = me.getAllRoleGrid();
    	me.moveGridSelectedDataToOtherGrid(srcGrid,targetGrid);
    	me.setUserEditDirty();
    },
    onUserEditWindowBeforeshowFire : function(win,opts){
    	var me = this;
    	//获取权限树数据
    	var userId = win.userId;
    	me.getAuthTreeDataByUserId(userId);
    },
    onUserAuthTreeCheckChgFire : function(node,checked,opts){
    	var me = this;
    	ChildCheck(node,checked);
    	ParentCheck(node,checked);
    	me.setAuthTreeDataFromChecked();
    	me.setUserEditDirty();
    },
    onBtnSaveUserInfoFire : function(btn,evt,opts){
    	var me = this;
    	var winDirty = me.isUserEditDirty();
    	if(!winDirty){
    		ShowInfoMsg('提交提示','未对当前界面进行数据操作，不需要提交');
    		return;
    	}
    	me.saveUserInfoByAction(btn.module,btn.action);
    },
    onBtnDelUsersFire : function(btn,evt,opts){
    	var me = this;
    	Ext.MessageBox.show({
    		title : '批量删除用户',
    		msg : '删除用户不可恢复，是否确认操作？',
    		width : 200,
    		buttons : Ext.MessageBox.OKCANCEL,
    		icon : Ext.MessageBox.WARNING,
    		fn : me.onDelUsersConfirm,
    		scope : this
    	});
    },
    /*********************************事件监听触发函数End*************************************/
    
    /*********************************前端业务处理函数Start*************************************/
    showUserEditWindow : function(cfg){
    	var me = this;
        var userEditWindow = new Service.user.view.UserEditWindow(cfg);
        if(cfg.window_action=='chg'){
        	var form = me.getUserEditForm();
        	form.loadRecord(cfg.record);
        }
        userEditWindow.show();
        return userEditWindow;
    },
    activeUserEditTab : function(tab,acTab){
    	if(acTab)
    		tab.setActiveTab(acTab);
    },
    setWindowNavButtonDisabled : function(acTab){
    	var pbtn = Ext.getCmp('Service_user_btn_active_prevUserEditTab');
    	var nbtn = Ext.getCmp('Service_user_btn_active_nextUserEditTab');
    	if(pbtn && nbtn){
    		if(acTab.previousSibling() == null){
	    		pbtn.setDisabled(true);
	    		nbtn.setDisabled(false);
	    	}else if(acTab.nextSibling() == null){
	    		pbtn.setDisabled(false);
	    		nbtn.setDisabled(true);
	    	}else{
	    		pbtn.setDisabled(false);
	    		nbtn.setDisabled(false);
	    	}
    	}
    },
    setUserRoleInfoDisplay : function(textValue){
    	var field = Ext.getCmp('Service_user_displayfield_roleInfo_display');
    	field.setValue(textValue);
    },
    
    moveGridSelectedDataToOtherGrid : function(srcGrid,targetGrid){
    	//1、获取源grid的select数据
    	//2、添加数据到目标grid
    	//3、删除源grid的select数据
    	if(!srcGrid || !targetGrid)
    		return false;
    	var selections = srcGrid.getSelectionModel().getSelection();
    	if(!selections || selections.length==0)
    		return false;
    	srcGrid.getSelectionModel().deselectAll();
    	targetGrid.getStore().add(selections);
    	srcGrid.getStore().remove(selections);
    	return true;
    },
    
    setAuthTreeData : function(treePanel,rootData){
		treePanel.setRootNode(rootData);
    	treePanel.expandAll();
    },
    
    setAuthTreeDataFromChecked : function(){
    	var me = this;
    	var nodes = me.getAllAuthTree().getChecked();
    	var selectAuthTree = me.getSelectAuthTree();
    	selectAuthTree.refreshTree(nodes);
    	selectAuthTree.expandAll();
    },
    
    setUserEditDirty : function(){
    	var me = this;
    	var editWindow = me.getUserEditWindow();
    	if(editWindow)
    		editWindow.dirty = true;
    },
    isUserEditDirty : function(){
    	var me = this;
    	var editWindow = me.getUserEditWindow();
    	return editWindow?(!!editWindow.dirty):false;
    },
    saveUserInfoByAction : function(module,action){
    	//1.获取usr form数据
    	//2.获取用户角色数据
    	//3.获取用户权限数据
    	//4.提交全部数据到服务端
    	var me = this;
    	var infos = me.getUserInfoValues();
    	var roles = me.getUserRoleIds();
    	var permissions = me.getUserPermissionValues();
    	me.saveUserToServer(module,action,infos,roles,permissions.mids,permissions.aids);
    },
    getUserInfoValues : function(){
    	var me = this;
    	var form = me.getUserEditForm();
    	var values = form.getValues();
    	return values;
    },
    getUserRoleIds : function(){
    	var me = this;
    	var rgrid = me.getSelectRoleGrid();
    	var datas = rgrid.getStore().data;
    	var rets = [];
    	datas.each(function(item,index,length){
    		rets.push(item.get('id'));
    	},me);
    	return rets;
    },
    getUserPermissionValues : function(){
    	var me = this;
    	var atree = me.getSelectAuthTree();
    	var rootNode = atree.getRootNode();
    	var moduleIds = [];
    	var actionIds = [];
    	function getIds(node){
    		if(node.hasChildNodes()){
    			var childs = node.childNodes;
    			for(var p in childs){
    				var tnode = childs[p];
    				if(tnode.get('type') == 'module')
    					moduleIds.push(tnode.get('id'));
    				else if(tnode.get('type') == 'action')
    					actionIds.push(tnode.get('actionId'));
    				getIds(tnode);
    			}
    		}
    	}
    	getIds(rootNode);
    	return {
    		mids : moduleIds,
    		aids : actionIds
    	};
    },
    /*********************************前端业务处理函数End*************************************/
    
    /*********************************数据处理及交互函数Start*************************************/
    
    getAuthTreeDataByUserId : function(userId){
    	var me = this;
    	me.request({
    		params: {
    			'module': 'Service_user',
    			'action': 'getUserValidModulesAndActionsForAuthTree',
    			'userId': userId
    		},
    		onSuccess : function(rs,opts,panel){
    			var records = rs.result;
				var root = {
					id : 1,
					text: '组织结构',
    				leaf: false,
    				moduleType: 0,
    				moduleText: '组织结构',
    				moduleName: 'root',
    				validFlag: true
				};
				root['children'] = me.getAuthTreeData(root,records);
				var allAuthTree = me.getAllAuthTree();
				me.setAuthTreeData(allAuthTree,root);
				me.setAuthTreeDataFromChecked();
    		}	
    	});
    },
    
   getAuthTreeData: function(root,records){
    	var me = this;
    	var moduleName = root.moduleName;
    	var children = [];
    	var recs = me.getAuthTreeModuleData(moduleName,records);
    	for(var i in recs){
    		var rec = recs[i];
    		var treeNode = {
    			pname: rec['pname'],
    			id: rec['id'],
    			moduleType: rec['moduleType'],
    			moduleName: rec['moduleName'],
    			checked: rec['checked'],
    			type: 'module'
    		};
    		if(rec['moduleType'] == 1){//目录
    			treeNode['text'] = '<font color="#006400">'+rec['moduleText']+'</font>';
    			treeNode['leaf'] = false;
    			treeNode['children'] = me.getAuthTreeData(rec,records);
    			children.push(treeNode);
    		}else if(rec['moduleType'] == 2){//功能
    			treeNode['text'] = '<font color="#8B4513">'+rec['moduleText']+'</font>';
    			treeNode['iconCls'] = 'icon-tree-modulenode';
    			if(!rec['actionModels'] || rec['actionModels'].length == 0){
    				treeNode['leaf'] = true;
    			}
    			else {
    				treeNode['leaf'] = false;
    				var actions = rec['actionModels'];
    				var c = [];
    				for(var j in actions){
    					var action = actions[j];
    					c.push({
    						text: '<font color="#008B8B">'+action['actionText']+'</font>',
    						leaf: true,
    						pname: action['moduleName'],
    						actionId: action['id'],
    						type: 'action',
    						checked: action['checked']
    					});
    				}
    				treeNode['children'] = c;
    			}
    			children.push(treeNode);
    			
    		}else{
    			console.log("初始化权限树数据异常，模块类型错误："+rec['moduleType']);
    		}
    	}
    	return children;
    },
    
    getAuthTreeModuleData: function(pname,records){
    	var ret = [],me = this;
    	Ext.each(records, function(record,index,self){
			if(record['pname'] == pname){
				ret.push(record);
			}
    	},me);
    	return ret;
    },
    
    saveUserToServer : function(module,action,userInfos,roleIds,moduleIds,actionIds){
    	var me = this;
    	Ext.applyIf(userInfos,{
    		'module' : module,
    		'action' : action,
    		'roleIds' : roleIds,
    		'moduleIds' : moduleIds,
    		'actionIds' : actionIds
    	});
    	me.request({
    		params : userInfos,
    		masker : me.getUserEditWindow(),
    		onSuccess : function(rs,opts,btn){
    			alert('保存成功');
    		},
    		onFailure : function(rs,opts,btn){
    			alert('保存失败');
    		}
    	});
    },
    delBatchUsers : function(userIds){
    	var me = this;
    	if(userIds && userIds.length>0){
    		me.request({
    			masker : me.getUserList(),
    			params : {
    				'userIds' : userIds,
    				'module' : 'Service_user',
    				'action' : 'delUsers'
    			},
    			scope : me,
    			onSuccess : function(rs,opts){
    				var list = me.getUserList();
    				var records = list.getSelectionModel().getSelection();
    				var store = list.getStore();
    				store.remove(records);
    				ShowInfoMsg('操作成功','用户已删除');
    			},
    			onFailure : function(rs,opts){
    				ShowInfoMsg('失败',rs.msg);
    			}
    		});
    	}
    }
    /*********************************数据处理及交互函数End*************************************/
});
